package com.shawn.engine;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Telephony;
import android.util.Log;
import android.util.Xml;

import com.shawn.mobliesafe.AToolsActivity;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by shawn on 2016/4/22.
 */
public class SMSEngine {

    public interface ShowProgress{
        void setMax(int max);
        void setProgress(int progress);
    }

    /**
     * 获取短信
     */
    public static void getAllSMS(Context context,ShowProgress showProgress){
        //1.获取短信
        //1.1获取内容解析者
        ContentResolver resolver = context.getContentResolver();
        //1.2获取内容提供者地址   sms,sms表的地址:null  不写
        //1.3获取查询路径
        Uri uri = Uri.parse("content://sms");
        //1.4.查询操作
        Cursor cursor = resolver.query(uri,new String[]{"address","date","type","body"},null,null,null);
        int count = cursor.getCount();
        showProgress.setMax(count);
        int progress = 0;


        //2.备份短信
        //2.1获取xml序列器
        XmlSerializer xmlSerializer = Xml.newSerializer();
        try {
            //2.2设置xml文件保存的路径
            //os : 保存的位置
            //encoding : 编码格式
            xmlSerializer.setOutput(new FileOutputStream(new File("/mnt/sdcard/backupsms.xml")), "utf-8");
            //2.3设置头信息
            //standalone : 是否独立保存
            xmlSerializer.startDocument("utf-8", true);
            //2.4设置根标签
            xmlSerializer.startTag(null,"smss");
            
            while(cursor.moveToNext()) {
                //2.5设置短信的标签
                xmlSerializer.startTag(null,"sms");
                //2.6设置文本内容的标签
                xmlSerializer.startTag(null,"address");
                String address = cursor.getString(0);
                //2.7设置文本内容
                xmlSerializer.text(address);
                xmlSerializer.endTag(null, "address");

                xmlSerializer.startTag(null, "count");
                xmlSerializer.text(count+"");
                xmlSerializer.endTag(null, "count");

                xmlSerializer.startTag(null, "date");
                String date = cursor.getString(1);
                xmlSerializer.text(date);
                xmlSerializer.endTag(null, "date");

                xmlSerializer.startTag(null, "type");
                String type = cursor.getString(2);
                xmlSerializer.text(type);
                xmlSerializer.endTag(null, "type");

                xmlSerializer.startTag(null, "body");
                String body = cursor.getString(3);
                xmlSerializer.text(body);
                xmlSerializer.endTag(null, "body");

                xmlSerializer.endTag(null, "sms");
                progress++;
                showProgress.setProgress(progress);
            }
            xmlSerializer.endTag(null,"smss");
            xmlSerializer.endDocument();
            //2.8将数据刷新到文件中
            xmlSerializer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void restoreAllSMS(Context context,ShowProgress showProgress) {

        XmlPullParser parser = Xml.newPullParser();
        try {
            parser.setInput(new FileInputStream(new File("/mnt/sdcard/backupsms.xml")), "utf-8");
            ContentValues values = null;
            int type = parser.getEventType();
            int progress = 0;
            while (type != XmlPullParser.END_DOCUMENT) {//如果没有到文件的结尾 则一直执行
                switch (type) {
                    case XmlPullParser.START_TAG://起始节点
                        if ("sms".equals(parser.getName())) {//但是信息节点的时候新建一个contentValues
                            values = new ContentValues();
                        } else if ("address".equals(parser.getName())) {
                            type = parser.next();
                            values.put("address", parser.getText());
                        } else if ("date".equals(parser.getName())) {
                            type = parser.next();
                            values.put("date", parser.getText());
                        } else if ("type".equals(parser.getName())) {
                            type = parser.next();
                            values.put("type", parser.getText());
                        } else if ("body".equals(parser.getName())) {
                            type = parser.next();
                            values.put("body", parser.getText());
                        }else if("count".equals(parser.getName())) {
                            type = parser.next();
                            showProgress.setMax(Integer.parseInt(parser.getText()));
                        }
                        break;
                    case XmlPullParser.END_TAG: {
                        String smsPackage = Telephony.Sms.getDefaultSmsPackage(context);
                        String packageName = context.getPackageName();
                        if (!smsPackage.equals(packageName)) {
                            //如果这个App不是默认的Sms App，则修改成默认的SMS APP
                            //因为从Android 4.4开始，只有默认的SMS APP才能对SMS数据库进行处理
                            Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
                            intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, packageName);
                            context.startActivity(intent);
                        }

                        if ("sms".equals(parser.getName())) {//如果节点是sms
                            Uri uri = Uri.parse("content://sms");
                            ContentResolver resolver = context.getContentResolver();
                            resolver.insert(uri, values);//先数据库中插入数据
                            values = null;

                            progress++;
                            showProgress.setProgress(progress);//设置进度

                        }
                    }
                }
                type = parser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
